import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import * as constants from '../../../providers/Constants'
import { NavController, AlertController } from '@ionic/angular';
import { ToastService } from './../../../providers/toast/toast.service'
import { Storage } from 'src/app/providers/Storage';
import { AuthService } from 'src/app/services/auth.service';
import { Utils } from 'src/app/providers/Utils';
import { ActivatedRoute, Params } from '@angular/router';
import { Facebook, FacebookLoginResponse } from '@ionic-native/facebook/ngx';
import * as WebIM from '../../../../../src/webimSDK3.0.6.js'
import * as MessageUtlis from 'src/app/providers/MessageUtlis';
import { GooglePlus } from '@ionic-native/google-plus/ngx';
import { SignInWithApple,    AppleSignInResponse, AppleSignInErrorResponse,  ASAuthorizationAppleIDRequest } from '@ionic-native/sign-in-with-apple/ngx';

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
  // 验证码倒计时
  verifyCode: any = {
    verifyCodeTips: "Get code",
    countdown: constants.DEFAULT_SMS_TIME,
    disable: true
  }
  isCheck: boolean = false;
  storagePsw: boolean = true;
  // 验证码倒计时     
  signInfo: any = {
    userPhone: "",
    code: "",
    userPassword: '',
  }
  pageType: number = 0;
  loginIndex: number = 0;
  testRegister = '1';
  connUtils: any = {};
  userPhone: any = {};
  constructor(private toast: ToastService,
    private alertController: AlertController, 
    private ref: ChangeDetectorRef,
     private fb: Facebook,
    private googlePlus: GooglePlus,
    private activeRoute: ActivatedRoute,
    public nav: NavController,
    public service: AuthService, 
    private signInWithApple: SignInWithApple,
    ) {
    this.activeRoute.queryParams.subscribe((params: Params) => {
      this.pageType = params.pageType;
    });
  }

  ngOnInit() {
    let psw = Storage.localStorage.get('userPsw');
    if (psw != null) {
      this.signInfo.userPhone = psw.userPhone
      this.signInfo.userPassword = psw.userPassword
    }
    this.connUtils = MessageUtlis.MessageUtlis.getConn();
  }
  skip() {
    this.nav.navigateRoot('/tabs/tab1');
  }
  onGOOGLE() {
    this.googlePlus.login({})
      .then(res => {

        Storage.localStorage.set('GoogleEmail', res.email);
        this.service.googleLogin({
          accessToken: res.accessToken,
        }).subscribe(res => {
          console.log("resBBBBBBBBBB",res) 
          // 保存成功返沪上一页，否则弹出提示框
          if (res.retCode == '000000') {
            console.log("google",JSON.stringify(res))
            Storage.localStorage.set('token', res.userInfo.userPhone);
            Storage.localStorage.set('thirdLogin', 'google');
            Storage.localStorage.set('userInfo', res.userInfo);
            Storage.localStorage.set('userPhone', res.userInfo.userPhone);
            this.userPhone = res.userInfo.userPhone;
          //  this.nav.navigateRoot('/tabs/tab1'); 
            //this.registerUser(this.connUtils);
            this.getUserInfo('google'); 
          } else if (constants.errCode[res.retCode]) {
            if (constants.errCode[res.retCode] != '0') {
              this.toast.show(constants.errCode[res.retCode]);
            }
          } else if (res.retMsg) {
            this.toast.show(res.retMsg);
          } else {
            this.toast.show("exception service routine");
          }
        });
        
        
      })
      .catch(err =>{
        console.log("errBBBBBB",err)
        this.toast.show(JSON.stringify(err));
       
 
     
      });
  }
  onFacebook() {
    // this.toast.show('暂未开通');
    this.fb.login(['public_profile', 'email']).then((res: FacebookLoginResponse) => {
      console.log('faceBook==', res);
      if (res.authResponse.accessToken) {
        this.service.faceBookLogin({
          accessToken: res.authResponse.accessToken,
        }).subscribe(res => {
          console.log('faceBook登陆的日志', res);
          // 保存成功返沪上一页，否则弹出提示框
          if (res.retCode == '000000') {
            
            Storage.localStorage.set('token', res.userInfo.userPhone);
            Storage.localStorage.set('thirdLogin', 'facebook');

            Storage.localStorage.set('userInfo', res.userInfo);
            Storage.localStorage.set('userPhone', res.userInfo.userPhone);
            this.userPhone = res.userInfo.userPhone;
           // this.nav.navigateRoot('/tabs/tab1');
          //  this.registerUser(this.connUtils);
            this.getUserInfo('facebook');
          } else if (constants.errCode[res.retCode]) {
            if (constants.errCode[res.retCode] != '0') {
              this.toast.show(constants.errCode[res.retCode]);
            }
          } else if (res.retMsg) {
            this.toast.show(res.retMsg);
          } else {
            this.toast.show("exception service routine");
          }
        });
      } else {
        this.toast.show('Failed to obtain user information');
      }
    })
      .catch(e => {
        this.toast.show('fail');
      });
  }

  close() {
    console.log('后退了');

    this.nav.pop();
  }
  clear() {
    this.signInfo.userPhone = '';
  }
  async  aaa(){
  
    this.signInWithApple.signin({
      requestedScopes: [
        ASAuthorizationAppleIDRequest.ASAuthorizationScopeFullName,
        ASAuthorizationAppleIDRequest.ASAuthorizationScopeEmail
      ]
    })
    .then((res: AppleSignInResponse) => {
      // https://developer.apple.com/documentation/signinwithapplerestapi/verifying_a_user
      console.log('Send token to apple for verification: ' + JSON.stringify(res));
     
      this.appleLog(res)
    })
    .catch((error: AppleSignInErrorResponse) => {
      this.toast.show('Failed to obtain user information');
    });
   

    
  }
  appleLog(apple){
    
  
    let data = {
     identityToken:apple.identityToken,
     userID:apple.user,
   }
   console.log('登录传的参数' + JSON.stringify(data));
   this.service.appleLog(data).subscribe(res => {

    
     console.log('登录成功' + JSON.stringify(res));
     // 保存成功返沪上一页，否则弹出提示框
     if (res.retCode == '000000') {

      Storage.localStorage.set('token', res.userInfo.userPhone);
      Storage.localStorage.set('thirdLogin', 'apple');
      Storage.localStorage.set('userPhone', res.userInfo.userPhone);
      this.userPhone = res.userInfo.userPhone;
     // this.nav.navigateRoot('/tabs/tab1');
     // this.registerUser(this.connUtils);
      this.getUserInfo('apple'); 

     } else if (res.retMsg) {
       this.toast.show(res.retMsg);
     } else {
       this.toast.show("exception service routine");
     }
   });
 }
  login() {
   
    // this.nav.navigateForward('contract-subcontract');
    //android 需要微信支付需要在 Wechat.java 的getSavedAppId 方法里面配置appkey
    // this.checkWeChat({});
    if (!this.signInfo.userPhone) {
      this.toast.show('The mailbox cannot be empty');
    } else if (!this.signInfo.userPassword) {
      this.toast.show('The password cannot be empty');
    } else if (this.signInfo.userPassword.length < 6) {
      this.toast.show('The password cannot be empty');
    } else {
      let data = {
        userPhone: this.signInfo.userPhone,
        userPassWord: this.signInfo.userPassword,
        // code: this.signInfo.code
      }
      this.service.login(data).subscribe(res => {
        // 保存成功返沪上一页，否则弹出提示框
        if (res.retCode == '000000') {
          Storage.localStorage.set('thirdLogin','login');
          if (this.storagePsw) {
            let psw = {
              userPhone: this.signInfo.userPhone,
              userPassword: this.signInfo.userPassword,
            }
            Storage.localStorage.set('userPsw', psw);
          } else {
            Storage.localStorage.remove('userPsw');
          }
          Storage.localStorage.set('token', this.signInfo.userPhone);
          Storage.localStorage.set('userInfo', res.userInfo);
          Storage.localStorage.set('userPhone', this.signInfo.userPhone);
          this.userPhone = this.signInfo.userPhone;
        //  this.registerUser(this.connUtils);
          //this.nav.navigateRoot('/tabs/tab1');
           this.getUserInfo('log');
        } else if (constants.errCode[res.retCode]) {
          if (constants.errCode[res.retCode] != '0') {
            this.toast.show(constants.errCode[res.retCode]);
          }
        } else if (res.retMsg) {
          this.toast.show(res.retMsg);
        } else {
          this.toast.show("exception service routine");
        }
      });
    }
  }

  getUserInfo(name) {
    this.service.getUserInfo().subscribe(res => {
        console.log("6666666666666",JSON.stringify(res))
      
        
        
      // 保存成功返沪上一页，否则弹出提示框
       if (res.retCode == '000000') {

        let userInfo=   Storage.localStorage.get('userInfo');
        console.log("7777777",JSON.stringify(userInfo))
        userInfo.avatarUrl=res.info.avatarUrl;
        userInfo.sex=res.info.sex;
        userInfo.uesrBirthday=res.info.uesrBirthday;
        userInfo.userIp=res.info.userIp;

        Storage.localStorage.set('userInfo', userInfo);
        this.nav.navigateRoot('/tabs/tab1');

     
      }  else if (res.retMsg) {
        this.toast.show(res.retMsg);
      } else {
        this.toast.show("exception service routine");
      }
    });
  }
  getSms() {
    if (!this.signInfo.userPhone) {
      this.toast.show('The mailbox cannot be empty');
    } else {
      if (this.verifyCode.disable) {
        let data = {
          mobilePhone: this.signInfo.userPhone,
          smsType: '0'
        }
        this.service.getSms(data).subscribe(res => {
          // 保存成功返沪上一页，否则弹出提示框
          if (res.retCode == '000000') {
            this.toast.show("successful");
            this.settime();
          } else {
            if (constants.errCode[res.retCode]) {
              if (constants.errCode[res.retCode] != '0') { this.toast.show(constants.errCode[res.retCode]); }
            } else if (res.retMsg) {
              this.toast.show(res.retMsg);
            } else {
              this.toast.show("failure");
            }
          }
        });
      }
    }
  }
  // 倒计时
  settime() {
    if (this.verifyCode.countdown == 1) {
      this.verifyCode.countdown = constants.DEFAULT_SMS_TIME;
      this.verifyCode.verifyCodeTips = "Get code";
      this.verifyCode.disable = true;
      return;
    } else {
      this.verifyCode.disable = false;
      this.verifyCode.countdown--;
    }
    this.verifyCode.verifyCodeTips = "Get (" + this.verifyCode.countdown + ")";
    setTimeout(() => {
      this.verifyCode.verifyCodeTips = "Get (" + this.verifyCode.countdown + ")";
      this.settime();
    }, 1000);
  }







  //注册
  registerUser(conn) {
   
    let nickName = '';
    let userInfo = Storage.localStorage.get('userInfo');
    // if (userInfo) {
    //   nickName=userInfo.userNickName
    // }else{
    //   nickName= this.phone
    // }
    var options = {
      username: this.userPhone.replace('@', '') + this.testRegister,
      password: '123',
      nickname: this.userPhone,
      appKey: WebIM.config.appkey,
      success: this.successData(),
      error: this.errorData(),
      // success: function (message) {
      //   console.log('message', message);
      // },
      apiUrl: WebIM.config.apiURL
    };
    console.log('conn', conn);
 
    conn.registerUser(options);
  }

  successData() {
    console.log('成功==');
  }
  errorData() {
    console.log('注册失败了');
    let lmsg = Storage.localStorage.get('IS_MSG_LOGIN');
    let time = 0;
    if (!lmsg) {
      console.log('有延迟');
      time = 500;
      Storage.localStorage.set('IS_MSG_LOGIN', '1');
    }
    setTimeout(res => {
      this.open(this.connUtils);
      MessageUtlis.MessageUtlis.listen(this.connUtils, (callBack, type) => {
        console.log('callBack=', callBack);
        this.loginIndex = 0;
        if (!callBack) {
          this.loginHX(callBack)
        }
      });
    }, time)

  }
  loginHX(callBack) {
    if (!callBack) {
      this.open(this.connUtils);
      MessageUtlis.MessageUtlis.listen(this.connUtils, (callBack, type) => {
        // this.loginHX(callBack)
        this.loginIndex = 0;
      });
    }
  }

  //登录
  open(conn) {
    if (this.loginIndex == 0) {
      this.loginIndex = this.loginIndex + 1;
      var options = {
        apiUrl: WebIM.config.apiURL,
        // user: this.uid,
        user: this.userPhone.replace('@', '') + this.testRegister,
        // pwd: this.phone,
        pwd: '123',
        appKey: WebIM.config.appkey,
        success: function (token) {
          // var token = token.access_token;
          // WebIM.utils.setCookie('webim_', token, 1);
          console.log('登录成功', token);
        },
        error: function () {
          // this.loginHX(false);
          console.log('登录失败');
        }
      };
      conn.open(options);
    }


  }
}
